<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>群聊</title>
    <script src="/webjars/jquery/3.6.4/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/1.5.1/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/2.3.4/stomp.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;

        //切换各个组件的显示与隐藏
        function show(flag) {
            $("#connect").prop("disabled", flag);
            $("#disconnect").prop("disabled", !flag);
            if (flag == true) {
                $("#chatRoom").show();
                $("#user").text($("#name").val());
            } else {
                $("#charRoom").hide();
            }
        }

        //连接到WebSocket
        function connectWebsocket() {
            if (!$("#name").val()) {
                alert("请输入用户名！");
                return;
            }
            var url = "http://localhost:8080/webSocket";
            var socket = new SockJS(url);
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                show(true);
                stompClient.subscribe('/topic/receiveAll', function (data) {
                    showMsg(JSON.parse(data.body));
                });
            });
        }

        //展示消息
        function showMsg(message) {
            $("#chating").append("<div>" + message.name + ":" + message.content + "</div>");
        }

        //关闭连接
        function closeWebSocket() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            show(false);
        }

        //客户端发送消息
        function sendMsg() {
            stompClient.send("/app/sendAll", {}, JSON.stringify({
                'name': $("#name").val(),
                'content': $("#content").val(),
            }));
            $("#content").val("");
        }

        $(function () {
            $("#connect").click(function () {
                connectWebsocket();
            });
            $("#disconnect").click(function () {
                closeWebSocket();
            });
            $("#send").click(function () {
                sendMsg();
            });
        });
    </script>
</head>
<body>
<div>
    <label for="name">用户名</label>
    <input type="text" id="name" placeholder="用户名">
    <button id="connect" type="button">进入聊天室</button>
    <button id="disconnect" type="button" disabled="disabled">退出聊天室</button>
</div>
<br>
<div id="chatRoom" style="display: none">
    <div id="chating" style="border:1px solid #ccc;width: 400px;height: 400px">
    </div>
    <br>
    <div>
        <label for="name"><span id="user"></span>说：</label>
        <input type="text" id="content" placeholder="请输入聊天内容">
        <button id="send" type="button">发送</button>
    </div>
</div>
</body>
</html>